package com.bussiness.xutai.controller;

import com.bussiness.xutai.bean.RegisterUser;
import com.bussiness.xutai.bean.RespBean;
import com.bussiness.xutai.bean.User;
import com.bussiness.xutai.service.UserService;
import com.bussiness.xutai.util.MD5Util;
import com.bussiness.xutai.util.PhoneCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import static org.apache.solr.client.solrj.impl.XMLResponseParser.log;

@Controller
public class RegisterController {
    @Autowired
    UserService userService;

    @RequestMapping("getCode")
    @ResponseBody
    public RespBean getCode(String phone){
        boolean getCode = PhoneCode.getPhonemsg(phone);
        if(getCode){
            log.info("验证已发送");
            return RespBean.ok("验证码发送成功");

        }else {
            log.info("验证码发送失败");
            return RespBean.error("验证码发送失败");

        }
    }

    @RequestMapping("register")
    @ResponseBody
    public RespBean register(String password, String phone, String code){
        if(code == null){
            log.info("验证码为空");
            return RespBean.error("验证码不能为空");
        }
        boolean register = PhoneCode.codeIsTure(code);
        if(!register){
            log.info("验证码不正确");
            return RespBean.error("验证码不正确");
        }

        User user = null;
        user = userService.getUserByAccount(phone);
        if(ObjectUtils.isEmpty(user)){
            User newUser = new User();
            newUser.setAccount(phone);
            newUser.setPassword(MD5Util.encrypt(password));
            boolean save = userService.saveUser(newUser);
            if(save) {
                log.info("注册成功");
                return RespBean.ok("注册成功");
            }else {
                log.info("注册失败");
                return RespBean.error("注册失败");
            }
        }else {
            log.info("用户名已存在");
            return RespBean.error("用户名已存在");
        }
    }

}
